<script setup lang="ts">

import { ref, onMounted } from 'vue'
import { Message } from '@arco-design/web-vue'
import { useRoute, useRouter } from 'vue-router'
import { usePaperStore } from '../stores/papers'
import { type ITestPaper, TestItem } from '../lib/test'
import MarkdownEditor from '@/components/MarkdownEditor.vue'

const router = useRouter()
const route = useRoute()

// 试卷加载器
const { loadPaper } = usePaperStore()

// 状态
const isLoading = ref(true)

// 错误
const error = ref<string | null>(null)

// 试卷对象
const paper = ref<ITestPaper | null>(null)
loadPaper(route.params.paperName as string).then((_paper) => {
    isLoading.value = true
    paper.value = _paper
}).catch((e) => {
    error.value = e.message
}).finally(() => {
    setTimeout(() => isLoading.value = false, 300)
})


// 当前编辑的试题
const currentItem = ref<TestItem | null>(null)

// 编辑item
const editItem = (item: TestItem) => {
    currentItem.value = item
}

// 删除item
const removeItem = (item: TestItem) => {
    if (item === currentItem.value) currentItem.value = null
    paper.value!.removeTestItem(item)
}

// 插入item
const insertItem = (item: TestItem, index: number) => {
    const newItem = { ...item }
    newItem.title = `(复制)${item.title} `
    newItem.id = `${newItem.id}-${new Date().getTime()}`
    paper.value!.addTestItem(newItem, index + 1)
    editItem(newItem)
}

// 格式化item
const formatItem = (item: TestItem) => [
    { label: "id", value: item.id },
    { label: "分类", value: item.category },
    { label: "排序", value: item.sortId },
]

const addItem = () => {

    const lastItem = paper.value!.items.at(-1)

    let newId: string

    let newCategory: string

    let newSortId: number

    if (lastItem) {
        const [category, num] = lastItem.id.split("-")
        newId = `${category}-${Number(num) + 1}`
        newCategory = lastItem.category
        newSortId = lastItem.sortId + 1
    } else {
        newId = "0"
        newCategory = "new category"
        newSortId = 0
    }

    const item = new TestItem(
        newId,
        "new title",
        "new content",
        5,
        paper.value!.name,
        newCategory,
        new Date().getTime(),
        newSortId
    )
    paper.value!.addTestItem(item)

    editItem(item)
}


const exportJson = () => {

    const json = {
        name: paper.value!.name,
        description: paper.value!.description,
        "test-items": {} as any
    }

    for (const item of paper.value!.items) {
        const category = item.category
        if (!json["test-items"][category]) json["test-items"][category] = []
        json["test-items"][category].push(item)
    }

    const blob = new Blob([JSON.stringify(json, null, 4)], { type: "application/json" })
    const url = URL.createObjectURL(blob)
    const a = document.createElement("a")
    a.href = url
    a.download = `${paper.value!.name}.json`
    a.click()
    URL.revokeObjectURL(url)
}

</script>


<template>

    <div v-if="error" class="flex justify-center items-center h-full w-full">
        {{ error }}
    </div>

    <div v-else-if="isLoading" class="flex justify-center items-center h-full w-full">
        <a-spin tip="加载中..." />
    </div>

    <div v-else-if="paper" class="flex h-full w-full gap-1">

        <div class="flex flex-col w-2/6 p-1 gap-1 ">

            <div class="flex p-1 bg-white rounded-md">
                <a-space>
                    <a-button size="mini" type="primary" @click="addItem">增加</a-button>
                    <a-button size="mini" type="primary" status="success" @click="exportJson">导出</a-button>
                    <a-button size="mini" type="primary" @click="router.back()">返回</a-button>
                    <div>数量：{{ paper.items.length }}</div>
                </a-space>


            </div>

            <div class=" flex flex-col flex-1 p-1 gap-2 bg-white overflow-auto rounded-md">

                <template v-for="(item, index) in paper.items" :key="item.id">

                    <div class="flex flex-col p-2 gap-2"
                        :class='[currentItem === item ? "bg-amber-100" : "bg-amber-50"]'>

                        <div>
                            <a-typography-paragraph :ellipsis="{ rows: 2 }">
                                {{ item.title }}
                            </a-typography-paragraph>
                        </div>

                        <div style="color:#666;font-size: 12px;">
                            <a-descriptions :value-style="{ color: '#999' }" :data="formatItem(item)" size="mini"
                                :column="1" />
                        </div>

                        <a-space>
                            <a-button size="mini" @click="insertItem(item, index)">插入</a-button>
                            <a-button size="mini" @click="editItem(item)">修改</a-button>
                            <a-button size="mini" @click="removeItem(item)">删除</a-button>
                        </a-space>

                    </div>

                </template>


            </div>
        </div>


        <div class="flex flex-1 rounded-md bg-white overflow-auto ">

            <div class="w-full h-full  p-5" v-if="currentItem">

                <a-space style="margin-bottom: 20px;">
                    <a-button size="mini" type="primary" @click="currentItem = null">关闭</a-button>
                </a-space>

                <a-form size="small" v-model="currentItem" layout="vertical">

                    <a-form-item field="title" label="问题">
                        <MarkdownEditor v-model="currentItem.title"></MarkdownEditor>
                    </a-form-item>

                    <a-form-item field="content" label="答案">
                        <MarkdownEditor v-model="currentItem.content"></MarkdownEditor>
                    </a-form-item>

                    <a-form-item field="id" label="id">
                        <a-input v-model="currentItem.id" placeholder="请请填写id" />
                    </a-form-item>

                    <a-form-item field="level" label="难度">
                        <a-select v-model="currentItem.level">
                            <a-option value="0">0</a-option>
                            <a-option value="1">1</a-option>
                            <a-option value="2">2</a-option>
                            <a-option value="3">3</a-option>
                            <a-option value="4">4</a-option>
                        </a-select>
                    </a-form-item>

                    <a-form-item field="category" label="分类">
                        <a-input v-model="currentItem.category" placeholder="请请填写分类" />
                    </a-form-item>

                    <a-form-item field="sortId" label="排序">
                        <a-input-number v-model="currentItem.sortId" placeholder="请请填写排序" />
                    </a-form-item>

                </a-form>

            </div>

            <div v-else class="w-full h-full flex justify-center items-center">
                <a-empty>
                    <template #image>
                        <icon-exclamation-circle-fill />
                    </template>
                    未选择
                </a-empty>
            </div>

        </div>



    </div>

</template>

<style>
.arco-spin-tip {
    color: #666
}

div.arco-typography,
p.arco-typography {
    margin-bottom: 0 !important;
}
</style>
